// pages/shoppingCart/shoppingCart.js
let app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // isSettlement: false, // 是否可结算

    topIsEdit: false, // 顶部是否编辑
    allRadio: false, // 是否全选
    isShowDiscountLayer:false, // 是否显示底部优惠弹层
    isShowSkuLayer:false, // 是否显示sku弹层
    yesShoppingList:[], // 购物车列表，不包含失效商品
    shoppingList:[], // 购物车列表，和失效列表合并
    // selectGoodIds:[], // 选中的商品id

    commodityItem: {}, // 点击到的商品
    clickOneIndex: 0, // 点击到的一级索引
    clickTwoIndex: 0, // 点击到的二级索引

    // isEmptyShopping: false, // 购物车是否为空
    selectGoodIds: [], // 选中的购物车id
    // selectGoodIdsList: [], // 选中的购物车id列表
    isSelectStatus: false, // 选中或取消状态
    skuList: [],
    skuItem: {}, // 选中的sku值
    clickSkuIndex: 0, // 选择的sku索引

    amountData: { // 调用api计算金额
      sumMoney: 0, // 总额
      totalMoney: 0, // 实际支付金额
      coupon_money: 0, // 优惠券金额
      purchase_money: 0, // 自购省金额
      ids: [], // 参与计算的id
    },
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    //判断onLaunch是否执行完毕
    if (app.globalData.checkLogin) {
      this.getShoppingList(); // 购物车列表
    } else {
      app.checkLoginReadyCallback = (res) => {
        this.getShoppingList(); // 购物车列表
      };
    }

    // this.setData({
    //   isEmptyShopping: false,
    // })

    // wx.setTabBarBadge({
    //   index: 2,
    //   text: '1'
    // })
  },

  // 结算按钮
  settlement(){
    let yesShoppingList = this.data.yesShoppingList;
    let shoppingList = this.data.shoppingList;

    // console.log("yesShoppingList---", yesShoppingList);

    let isSettlement = ''; // 是否跳转

    for (let i in shoppingList){
      if (shoppingList[i].id != -999){
        // console.log("shoppingList[i]---", shoppingList[i]);
        for (let j in  shoppingList[i].goods){
          console.log("shoppingList[i].goods[j].status---", shoppingList[i].goods[j].status);
          if (shoppingList[i].goods[j].status === true){
            isSettlement += true + ',';
          } else {
            isSettlement += false + ',';
          }
        }
      }
    }

    console.log("isSettlement---", isSettlement);

    if (isSettlement.indexOf('true') != -1){
      wx.navigateTo({
        url: '/pagesTwo/shop/paymentOrder/paymentOrder'
      })
    } else {
      wx.showToast({
        title: '请先选择商品',
        icon: 'none',
        duration: 2000
      })
    }
  },

  // 获取购物车列表
  getShoppingList(){
    let that = this;
    wx.showLoading({
      title: '加载中...',
    })
    // let yesShoppingList = this.data.yesShoppingList
    this.setData({
      shoppingList: [],
      yesShoppingList: [],
    })
    app.http({
      url: app.api.shoppingIndexShoppingList,
      data: {},
      //method: 'get',
    })
      .then((res) => {
        let requestData = res.data.data;
        // let yesShoppingList = [...requestData.shoppingList];
        // that.setData({
        //   yesShoppingList: yesShoppingList
        // })
        console.log("requestData---", requestData.shoppingList);
        // console.log("yesShoppingList---", yesShoppingList);
        if (requestData.shixiaoList.length){
          let invalidGoods = {
            id: -999,
            name: '失效商品',
            status: false,
            goods: requestData.shixiaoList
          };
          requestData.shoppingList.push(invalidGoods);
        }
        // requestData.shixiaoList.map(mapRes => {
        //   mapRes.name = '失效商品'
        // })

        let allRadio = false; // 是否选中底部全选
        requestData.shoppingList.map((shoppingListMap,shoppingListIndex) => {
          console.log("shoppingListMap.goods---", shoppingListMap.goods);
          let yesShoppingList = that.data.yesShoppingList
          yesShoppingList.push(...shoppingListMap.goods)
          that.setData({
            yesShoppingList: yesShoppingList
          })

          if (shoppingListMap.id != -999){
            for (let i in shoppingListMap.goods){
              if(shoppingListMap.goods[i].status == true) {
                shoppingListMap.status = true
                // allRadio = true
              } else {
                shoppingListMap.status = false
                // allRadio = false
                break; // 停止整个循环
              }
            }
          }
        })

        // 判断所有的店铺是否选中，所有店铺都选中时选中底部全选按钮
        for (let i in requestData.shoppingList){
          if (requestData.shoppingList[i].id != -999){
            console.log("requestData.shoppingList.status---", requestData.shoppingList[i].status);
            if(requestData.shoppingList[i].status == true) {
              allRadio = true
            } else {
              allRadio = false
              break; // 停止整个循环
            }
          }
        }


        console.log("shoppingList---", requestData.shoppingList);
        that.setData({
          shoppingList: requestData.shoppingList,
          allRadio: allRadio,
        })
        console.log("requestData---", requestData);

        that.calculationAmount(); // 计算金额
        wx.hideLoading()

        let isSettlement = ''; // 购物车是否为空

        for (let i in requestData.shoppingList){
          if (requestData.shoppingList[i].id != -999){
            // console.log("shoppingList[i]---", shoppingList[i]);
            for (let j in  requestData.shoppingList[i].goods){
              console.log("requestData.shoppingList[i].goods[j].status---", requestData.shoppingList[i].goods[j].status);
              if (requestData.shoppingList[i].goods[j].status === true){
                isSettlement += true + ',';
              } else {
                isSettlement += false + ',';
              }
            }
          }
        }

        if (isSettlement.indexOf('true') != -1){
          // that.setData({
          //   isEmptyShopping: false,
          // })
        } else {
          // that.setData({
          //   isEmptyShopping: true,
          // })
        }


      })
      .catch((err) => {

      });
  },


  // 顶部编辑按钮
  topEditBtn(){
    this.setData({
      topIsEdit: !this.data.topIsEdit
    })
  },

  // 点击选中或取消
  changeRadio(ev){
    let that = this;
    let allRadio = false;
    let item = ev.currentTarget.dataset.item;
    let index = ev.currentTarget.dataset.index;
    let inner_index = ev.currentTarget.dataset.inner_index;
    let radio_type = ev.currentTarget.dataset.radio_type;
    let shoppingList = this.data.shoppingList;
    let selectGoodIds = []; // 选中的购物车id
    let clickOneIndex = this.data.clickOneIndex; // 点击到的一级索引
    let clickTwoIndex = this.data.clickTwoIndex; // 点击到的一级索引
    // let selectGoodIdsList = this.data.selectGoodIdsList; // 选中的购物车id列表
    // let selectGoodIdsList = this.data.selectGoodIdsList; // 选中的购物车列表集合
    let isSelectStatus = false; // 选中或取消状态

    console.log("item---", item);
    console.log("index---", index);
    console.log("inner_index---", inner_index);
    console.log("radio_type---", radio_type);

    // 如果选择的是店铺radio
    if (radio_type == 'shopItem'){
      console.log("item---", item);
      // 判断是否全选该店铺商品
      if (!shoppingList[index].status){
        shoppingList[index].status = true
      } else {
        shoppingList[index].status = !shoppingList[index].status
      }
      isSelectStatus = shoppingList[index].status;
      // console.log(" shoppingList[index]---", shoppingList[index]);
      console.log(" isSelectStatus---", isSelectStatus);
      shoppingList[index].goods.map(mapRes => {
        console.log("mapRes.id---", mapRes.id);
        selectGoodIds.push(mapRes.id)
        mapRes.status = shoppingList[index].status
        // if (mapRes.status){
        //   selectGoodIdsList.push(mapRes.id)
        // }
      })
      console.log("shoppingList---", shoppingList);

      // 判断是否选中底部全选按钮
      for (let i in shoppingList){
        if (shoppingList[i].id != -999){
          if (shoppingList[i].status == true){
            allRadio = true
          } else {
            allRadio = false
            break; // 停止整个循环
          }
        }
      }
      console.log("-allRadio-----666---", allRadio);
      this.setData({
        allRadio: allRadio,
      })
    } else if (radio_type == 'item'){
      if (!item.status){
        item.status = true
        // isSelectStatus = true;
      } else {
        item.status = !item.status
        // isSelectStatus = !item.status;
      }
      console.log('item.status---',item.status)
      shoppingList[index].goods[inner_index] = item
      isSelectStatus = shoppingList[index].goods[inner_index].status


      console.log("select-item---", shoppingList);
      console.log('shoppingList[index].goods---',shoppingList[index].goods);

      selectGoodIds.push(item.id);

      let allRadio = false;
      // 如果选中该店铺所有的商品，则选中店铺，反之则取消选中店铺
      if (item.status){
        for (let i in shoppingList[index].goods){
          console.log("执行---222---shoppingList[index].goods[i]---",shoppingList[index].goods[i]);
          if(shoppingList[index].goods[i].status == true) {
            shoppingList[index].status = true
          } else {
            shoppingList[index].status = false
            allRadio = false;
            break; // 停止整个循环
          }
        }
      } else {
        shoppingList[index].status = false;
        allRadio = false;
      }

      // console.log("shoppingList-------------", shoppingList);
      // 选中商品时判断所有的店铺是否选中，所有店铺都选中时选中底部全选按钮
      for (let i in shoppingList){
        if (shoppingList[i].id != -999){
          console.log("shoppingList.status---", shoppingList[i].status);
          if(shoppingList[i].status == true) {
            allRadio = true
          } else {
            allRadio = false
            break; // 停止整个循环
          }
        }
      }

      this.setData({
        allRadio: allRadio
      })
      // selectGoodIdsList.push(selectGoodIds.join(','))
    } else if (radio_type == 'allItem'){
      console.log("radio_type---", radio_type);
      shoppingList.map(mapRes => {
        if (this.data.topIsEdit){
          mapRes.status = !this.data.allRadio
          mapRes.goods.map(goodsMap => {
            goodsMap.status = !this.data.allRadio
          })
        } else if (!this.data.topIsEdit && mapRes.id != -999){
          mapRes.status = !this.data.allRadio
          mapRes.goods.map(goodsMap => {
            goodsMap.status = !this.data.allRadio
          })
        }
      })
      selectGoodIds.push(0); // 全选传0
      // selectGoodIdsList = [0]

      this.setData({
        allRadio: !this.data.allRadio,
      })
      // console.log("allRadio---", this.data.allRadio);
      isSelectStatus = this.data.allRadio
    }

    console.log("shoppingList---", shoppingList);
    this.setData({
      shoppingList
    })
    console.log('ev---', ev);

    selectGoodIds = selectGoodIds.join(',');
    console.log("选中的购物车id---", selectGoodIds);
    console.log("isSelectStatus---", isSelectStatus);



    // console.log("this.data.selectGoodIdsList---", this.data.selectGoodIdsList);
    this.setData({
      selectGoodIds: selectGoodIds, // 选中的购物车id
      isSelectStatus: isSelectStatus, // 选中或取消状态
      // selectGoodIdsList: selectGoodIdsList, // 选中的购物车id列表
    })

    // 更改购物车状态
    this.setShoppingStatus({
      ids: selectGoodIds,
      status: isSelectStatus,
    });


    // let status = shoppingList[clickOneIndex].goods[clickTwoIndex].status;
    // let id = shoppingList[clickOneIndex].goods[clickTwoIndex].id;
    console.log("selectGoodIds-------99999------", selectGoodIds);
    console.log("isSelectStatus------88888------", isSelectStatus);

    // if (isSelectStatus){
    //   if (selectGoodIds.indexOf(',') != -1){
    //     let selectGoodIdsArray = selectGoodIds.split(',');
    //     // console.log("selectGoodIdsArray---", selectGoodIdsArray);
    //     selectGoodIdsArray.map(resMap => {
    //       selectGoodIdsList.push(resMap);
    //     })
    //   } else {
    //     selectGoodIdsList.push(selectGoodIds)
    //   }
    // } else {
    //   let selectGoodIdsArray = selectGoodIds.split(",");
    //   console.log("selectGoodIds.length-------7777-------", selectGoodIdsArray.length);
    //   selectGoodIdsArray.map(resMap => {
    //     selectGoodIdsList.map((selectGoodIdsListMap,selectGoodIdsListIndex) => {
    //       if (resMap == selectGoodIdsListMap){
    //         selectGoodIdsList.splice(selectGoodIdsListIndex,1);
    //       }
    //     })
    //   })
    // }
    // console.log("selectGoodIds-------666-------", selectGoodIdsList);

    // this.setData({
    //   selectGoodIdsList: selectGoodIdsList, // 选中的购物车id列表
    // })
    // console.log("------------666666666----------",this.data.commodityItem);
    // console.log("------------666666666-----selectGoodIdsList-----",selectGoodIdsList);
  },

  // 删除按钮
  delBtn(){
    let that = this;
    // let selectGoodIdsList = this.data.selectGoodIdsList; // 选中的购物车id数组
    let shoppingList = this.data.shoppingList; // 购物车列表
    let selectId = []; // 选中的购物车id

    shoppingList.map(resMap => {
      resMap.goods.map(goodsMap => {
        // console.log("goodsMap---",goodsMap);
        if (goodsMap.status){
          console.log("goodsMap----", goodsMap.id);
          selectId.push(goodsMap.id)
        }
      })
    })

    console.log("selectId---", selectId);

    if (this.data.topIsEdit){
      app.http({
        url: app.api.shoppingIndexDel,
        data: {
          ids: selectId.join(','),
        },
        //method: 'get',
      })
        .then((res) => {
          let requestData = res.data;
          console.log("requestData---", requestData);

          let isSettlement = ''; // 购物车是否为空

          if (requestData.code == 200){
            wx.showToast({
              title: '删除成功',
              icon: 'success',
              duration: 1500
            })
          }
          that.calculationAmount();  // 计算金额

          selectId.map(selectIdMap => {
            shoppingList.map((resMap,resIndex) => {
              resMap.goods.map((goodsMap,goodsIndex) => {
                if (goodsMap.id == selectIdMap){
                  console.log("goodsMap.id---111---", goodsMap.id);
                  console.log("goodsIndex---222---", goodsIndex);
                  resMap.goods.splice(goodsIndex,1);
                }

                console.log("goodsMap.status---", goodsMap.status);
              })
            })
          })
          that.setData({
            shoppingList: shoppingList
          })

          // 删除时，如果是全选状态，则去掉全选勾选
          if (that.data.allRadio){
            that.setData({
              allRadio: false
            })
          }


          for (let i in shoppingList){
            if (shoppingList[i].id != -999){
              // console.log("shoppingList[i]---", shoppingList[i]);
              for (let j in  shoppingList[i].goods){
                console.log("shoppingList[i].goods[j].status---", shoppingList[i].goods[j].status);
                if (shoppingList[i].goods[j].status === true){
                  isSettlement += true + ',';
                } else {
                  isSettlement += false + ',';
                }
              }
            }
          }

          if (isSettlement.indexOf('true') != -1){
            // that.setData({
            //   isEmptyShopping: false,
            // })
          } else {
            // that.setData({
            //   isEmptyShopping: true,
            // })
          }
        })
        .catch((err) => {

        });
    }
  },

  // 优惠卷弹层
  onCloseDiscountLayer() {
    this.setData({
      isShowDiscountLayer: !this.data.isShowDiscountLayer,
    });
  },

  // sku弹层
  onCloseSkuLayer(ev) {
    let item = ev.currentTarget.dataset.item;
    // console.log("点击sku---item---", item);
    this.setData({
      isShowSkuLayer: !this.data.isShowSkuLayer,
    });
    if (item){
      this.getSku({ // 获取商品sku
        id: item.goods_id,
        item: item,
      });
    }
  },

  // 数量选择进步器
  onChange(ev){
    let item = ev.currentTarget.dataset.item;
    let index = ev.currentTarget.dataset.index;
    let inner_index = ev.currentTarget.dataset.inner_index;
    let radio_type = ev.currentTarget.dataset.radio_type;
    let shoppingList = this.data.shoppingList;
    let number = ev.detail;

    // shoppingList[index].goods[inner_index].num = number
    //
    // this.setData({
    //   shoppingList
    // })

    // console.log("item---", item);
    // console.log("index---", index);
    // console.log("inner_index---", inner_index);
    // console.log("shoppingList---", shoppingList);
    // console.log('数量选择进步器---',number);

    // 请求更改购物车商品数量
    this.updateCommodityNum({
      number: number,
      index: index,
      inner_index: inner_index,
      id: item.id,
      num: number,
    });
  },

  // 选择弹框里的sku
  clickSku(ev){
    let item = ev.currentTarget.dataset.item;
    let index = ev.currentTarget.dataset.index;
    console.log("item---", item);
    this.setData({
      skuItem: item,
      clickSkuIndex: index,
    })
  },

  // 更新sku按钮
  updateSkuBtn(){
    let that = this;
    if (this.data.clickSkuIndex == -1){
      wx.showToast({
        title: '请选择商品规格',
        icon: 'none',
        duration: 1500
      })
    } else {
      app.http({
        url: app.api.shoppingIndexReAttr,
        data: {
          id: that.data.commodityItem.id, // 购物车列表id
          goods_id: that.data.commodityItem.goods_id, // 商品序号
          goods_attr_id	: that.data.skuItem.id, // 商品规格序号
        },
        //method: 'get',
      })
        .then((res) => {
          let requestData = res.data;
          let shoppingList = that.data.shoppingList;
          let clickOneIndex = that.data.clickOneIndex; // 点击到的一级索引
          let clickTwoIndex = that.data.clickTwoIndex; // 点击到的二级索引
          let attr_str = that.data.skuItem.attr_str; // 点击到的sku值
          // console.log("requestData---", requestData);
          // console.log("attr_str---", attr_str);
          // console.log("shoppingList---", shoppingList[clickOneIndex].goods[clickTwoIndex].attr_str);
          // shoppingList[that.data.clickOneIndex].goods.attr_str = that.data.skuItem.attr_str
          shoppingList[clickOneIndex].goods[clickTwoIndex].attr_str = attr_str
          // console.log("that.data.shoppingList---", that.data.shoppingList);
          that.setData({
            shoppingList: that.data.shoppingList,
            isShowSkuLayer: !that.data.isShowSkuLayer
          })
          that.calculationAmount();  // 计算金额
        })
        .catch((err) => {

        });
    }
  },

  // 点击商品item
  clickCommodityItem(ev){
    let index = ev.currentTarget.dataset.index;
    let inner_index = ev.currentTarget.dataset.inner_index;
    let inner_item = ev.currentTarget.dataset.inner_item;
    // console.log("index---", index);
    // console.log("inner_index---", inner_index);
    // console.log("inner_item--------------999999999999----------------", inner_item);

    this.setData({
      commodityItem: inner_item,
      clickOneIndex: index,
      clickTwoIndex: inner_index,
    })

  },

  /*
  * 获取商品规格
  * param id 商品id
  * param item 点击到的商品item
  * */
  getSku(param){
    let that = this;
    app.http({
      url: app.api.mallIndexGetGoodsAttr,
      data: {
        id: param.id,
      },
      //method: 'get',
    })
      .then((res) => {
        let requestData = res.data.data;
        console.log("requestData---", requestData);
        that.setData({
          skuList: requestData,
          skuItem: requestData[0],
        })

        requestData.map((resMap,resIndex) => {
          if (resMap.attr_str == param.item.attr_str){
            that.setData({
              clickSkuIndex: resIndex
            })
          }
        })
      })
      .catch((err) => {

      });
  },

  // 请求更改购物车商品数量
  /*
  * number 更改的数量
  * index 二维数组一级索引
  * inner_index 二维数组二级索引
  * id 商品id
  * num 数量
  * */
  updateCommodityNum(param){
    let that = this;
    let shoppingList = this.data.shoppingList;
    app.http({
      url: app.api.shoppingIndexEditNum,
      data: {
        id: param.id,
        num: param.num,
      },
      //method: 'get',
    })
      .then((res) => {
        let requestData = res.data;
        console.log("requestData---", requestData);
        if (requestData.code == 200){
          // wx.showToast({
          //   title: '添加成功',
          //   icon: 'success',
          //   duration: 1500
          // })
          console.log("param.index---", param.index);
          console.log("param.inner_index---", param.inner_index);
          console.log("param.number---", param.number);
          shoppingList[param.index].goods[param.inner_index].num = param.number

          that.setData({
            shoppingList
          })
        }
        that.calculationAmount();  // 计算金额
      })
      .catch((err) => {

      });
  },

  // 更改购物车选中状态
  /*
  * param ids 购物车id
  * param status 选中或取消
  * */
  setShoppingStatus(param){
    console.log("更改购物车选中状态---");
    console.log("param---",param);
    let that = this;
    if (!this.data.topIsEdit){
      app.http({
        url: app.api.shoppingIndexCheck,
        data: {
          ids: param.ids,
          status: param.status == true ? 1 : 0, // 状态值 1 为选中 0 为不选中
        },
        //method: 'get',
      })
        .then((res) => {
          let requestData = res.data.data;
          console.log("requestData---", requestData);
          that.calculationAmount();  // 计算金额
        })
        .catch((err) => {

        });
    }
  },

  // 计算金额
  calculationAmount(){
    let that = this;
    app.http({
      url: app.api.shoppingIndexShoppingListSumMoney,
      data: {},
      //method: 'get',
    })
      .then((res) => {
        let requestData = res.data.data;
        console.log("requestData---", requestData);
        that.setData({
          amountData: requestData
        })
      })
      .catch((err) => {

      });
  },

  // 获取手机授权弹层
  getPhone() {
    app.store.setState({
      getPhoneNumber: true,
    });
    console.log("获取手机授权弹层---");
    // that.onLoad(); // 刷新
  },


  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  // /**
  //  * 用户点击右上角分享
  //  */
  // onShareAppMessage: function () {
  //
  // }
})
